//
//  JKHomeTableViewController.swift
//  JKWeibo
//
//  Created by albert on 16/5/11.
//  Copyright © 2016年 albert. All rights reserved.
//  首页控制器

import UIKit
import SVProgressHUD

class JKHomeTableViewController: JKBaseTableViewController {
    
    //MARK: - 懒加载自定义popover转场动画管理
    private lazy var animationManager: JKPresentationManager = {
        let mgr = JKPresentationManager()
        let width: CGFloat = 200
        let height: CGFloat = 300
        let y: CGFloat = 55
        let x = (JKScreenW - width) * 0.5
        mgr.presentFrame = CGRect(x: x, y: y, width: width, height: height)
        return mgr
    }()
    
    //MARK: - 懒加载配图浏览器转场动画管理
    private lazy var browserManager: JKPresentManager = JKPresentManager()
    
    /** 保存所有的微博数据 */
    var statusListModel: JKStatusListModel = JKStatusListModel()
    
    //MARK: - 懒加载导航条标题按钮
    private lazy var titleBtn: JKTitleButton = {
        // 获取用户昵称
        let title = JKUserAccount.loadUserAccount()?.screen_name
        // 创建按钮
        let btn = JKTitleButton(type: UIButtonType.Custom)
        // 设置标题
        btn.setTitle(title, forState: UIControlState.Normal)
        // 注册点击事件
        btn.addTarget(self, action: "titleBtnClick:", forControlEvents: UIControlEvents.TouchUpInside)
        
        return btn
    }()
    
    /** 刷新提醒视图 */
    private var tipLabel: UILabel = {
        let lb = UILabel()
        
        lb.backgroundColor = UIColor.orangeColor().colorWithAlphaComponent(0.7)
        lb.text = "没有更多数据"
        lb.textColor = UIColor.whiteColor()
        lb.textAlignment = NSTextAlignment.Center
        let width = JKScreenW
        lb.frame = CGRect(x: 0, y: 0, width: width, height: 44)
        lb.hidden = true
        
        return lb
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 1.判断用户是否登录
        if !isLogin {
            visitorView?.setupVisitorViewInfo(nil, title: "关注一些人，回这里看看有什么惊喜")
            return
        }
        
        // 2.初始化导航条
        setupNav()
        
        // 3.获取微博数据
        loadNewData()
        
        // 4.设置tableView
        tableView.registerNib(UINib(nibName: "JKHomeCell", bundle: nil), forCellReuseIdentifier: "homeCell")
        tableView.registerNib(UINib(nibName: "JKForwardCell", bundle: nil), forCellReuseIdentifier: "forwardCell")
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        view.backgroundColor = JKGlobalBackGroundColor
        tableView.estimatedRowHeight = 400
        //tableView.rowHeight = UITableViewAutomaticDimension
        
        // 5.下拉刷新
        refreshControl = JKRefreshControl()
        refreshControl?.addTarget(self, action: "loadNewData", forControlEvents: UIControlEvents.ValueChanged)
        refreshControl?.beginRefreshing()
        
        // 6.添加刷新提醒控件到导航条
        navigationController?.navigationBar.insertSubview(tipLabel, atIndex: 0)
    }
    
    //MARK: - ===内部控制方法===
    /** loadNewData */
    @objc private func loadNewData() {
        
        statusListModel.loadNewData(lastCellFlag) { (models, error) -> () in
            // 1.安全校验
            if error != nil {
                SVProgressHUD.showErrorWithStatus("获取微博数据失败！")
                SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.Black)
                JKDispatchTool.after(JKTipDuration) { () -> Void in
                    SVProgressHUD.dismiss()
                }
                self.refreshControl?.endRefreshing()
            }
            
            // 2.关闭菊花
            self.refreshControl?.endRefreshing()
            
            // 3.显示刷新提醒
            self.showRefreshStatus(models?.count)
            
            // 4.刷新表格
            self.tableView.reloadData()
        }
    }
    
    /** 显示刷新提醒 */
    private func showRefreshStatus(count: Int?) {
        // 1.设置提醒文本
        tipLabel.text = ((count == 0) || count == nil ) ? "没有更多数据" : "\(count!) 条新微博"
        tipLabel.hidden = false
        
        // 2.执行动画
        UIView.animateWithDuration(1, animations: { () -> Void in
            // 设置动画自动回去，但是真机有bug？
            //UIView.setAnimationRepeatAutoreverses(true)
            
            self.tipLabel.transform = CGAffineTransformMakeTranslation(0, 44)
        }) { (_) -> Void in
            
            UIView.animateWithDuration(1, delay: 1, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
                self.tipLabel.transform = CGAffineTransformIdentity
                
            }, completion: { (_) -> Void in
                self.tipLabel.hidden = true
                // 2.关闭菊花
                self.refreshControl?.endRefreshing()
            })
        }
    }
    
    //MARK: 初始化导航条
    private func setupNav(){
        // 1.添加左右按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendattention", target: self, action: "leftBtnClick")
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action: "rightBtnClick")
        
        // 2.添加标题按钮
        navigationItem.titleView = titleBtn
        
        // 3.添加通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "titleChange", name: JKPresentationManagerDidPresentControllerNotification, object: nil)
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "titleChange", name: JKPresentationManagerDidDismissControllerNotification, object: nil)
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "showPicBrowser:", name: JKShowPicBrowserNotification, object: nil)
    }
    
    // 一定要移除通知
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    // MARK: - 弹出图片浏览器
    @objc private func showPicBrowser(noti : NSNotification) {
        // 注意：凡是通过网络或者通知获取到的数据，都需要进行安全校验
        guard let thumbUrls = noti.userInfo![JKThumbPicUrlsKey] as? [NSURL] else {
            SVProgressHUD.showErrorWithStatus("加载图片失败")
            SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.Black)
            JKDispatchTool.after(JKTipDuration) { () -> Void in
                SVProgressHUD.dismiss()
            }
            return
        }
        
        guard let bmiddlePicUrls = noti.userInfo![JKBmiddlePicUrlsKey] as? [NSURL] else {
            SVProgressHUD.showErrorWithStatus("加载大图失败")
            SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.Black)
            JKDispatchTool.after(JKTipDuration) { () -> Void in
                SVProgressHUD.dismiss()
            }
            return
        }
        
        guard let indexPath = noti.userInfo![JKIndexPathKey] as? NSIndexPath else {
            SVProgressHUD.showErrorWithStatus("获取索引失败")
            SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.Black)
            JKDispatchTool.after(JKTipDuration) { () -> Void in
                SVProgressHUD.dismiss()
            }
            return
        }
        
        // 1.创建图片浏览器，将所有图片和当前点击的索引传递给图片浏览器
        let browserVc = JKPicBrowserViewController(thumbUrls: thumbUrls, bmiddlePicUrls: bmiddlePicUrls, indexPath: indexPath)
        
        // 2.自定义转场动画
        // 设置转场动画代理
        browserVc.transitioningDelegate = self.browserManager
        // 设置转场动画样式
        browserVc.modalPresentationStyle = UIModalPresentationStyle.Custom
        
        // 3.设置其它数据
        guard let picCollectionView = noti.object as? JKPicCollectionView else{
            return
        }
        browserManager.setDefaultInfo(indexPath, browserDelegate: picCollectionView)
        
        // 4.弹出图片浏览器
        presentViewController(browserVc, animated: true, completion: nil)
    }
    
    //MARK: - 监听通知的方法
    @objc private func titleChange(){
        titleBtn.selected = !titleBtn.selected
    }
    
    //MARK: 标题按钮点击
    @objc private func titleBtnClick(btn: JKTitleButton){
        // 1.修改按钮的状态，这里不需要了，在通知里控制
        //btn.selected = !btn.selected
        
        // 2.显示菜单
        // 2.1创建菜单
        guard let menuVc = R.storyboard.popover.initialViewController else {
            return
        }
        
        // 自定义转场动画
        // 设置转场动画代理
        menuVc.transitioningDelegate = animationManager
        // 设置转场动画样式
        menuVc.modalPresentationStyle = UIModalPresentationStyle.Custom
        
        // 2.2弹出菜单
        presentViewController(menuVc, animated: true, completion: nil)
    }
    
    //MARK: 点击导航条左侧按钮
    @objc private func leftBtnClick(){
        JKLog("点击导航条左侧按钮")
    }
    
    //MARK: 点击导航条右侧按钮 扫一扫
    @objc private func rightBtnClick(){
        // 1.创建扫一扫控制器
        let vc = R.storyboard.jKQRCode.initialViewController!
        
        // 2.弹出扫一扫控制器
        presentViewController(vc, animated: true, completion: nil)
    }
    
    /** 缓存行高 */
    private var rowHeightCaches = [String : CGFloat]()
    
    // 清理缓存
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
        rowHeightCaches.removeAll()
    }
    
    /** 最后一条微博标记 */
    private var lastCellFlag = false
}

// MARK: - 数据源
extension JKHomeTableViewController {
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusListModel.statuses?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let viewModel = statusListModel.statuses![indexPath.row]
        
        let reuseIdentifier = (viewModel.status.retweeted_status != nil) ? "forwardCell" : "homeCell"
        
        // 1.创建cell
        let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier) as! JKHomeCell
        
        // 2.设置数据
        cell.viewModel = viewModel
        
        if indexPath.row == (statusListModel.statuses!.count - 1) {
            JKLog("最后一条微博\(viewModel.status.user?.screen_name)")
            lastCellFlag = true
            loadNewData()
            
        }else {
            lastCellFlag = false
        }
        
        // 3.返回cell
        return cell
    }
}

// MARK: - 代理
extension JKHomeTableViewController {
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        // 0.获取模型数据
        let viewModel = statusListModel.statuses![indexPath.row]
        let reuseIdentifier = (viewModel.status.retweeted_status != nil) ? "forwardCell" : "homeCell"
        
        // 1.从缓存中获取行高
        guard let height = rowHeightCaches[viewModel.status.idstr ?? "-1"] else {
            // 缓存中没有行高
            // 2.计算行高
            // 2.1获取当前对应行的cell
            guard let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier) as? JKHomeCell else {
                return 0
            }
            
            // 2.2缓存行高
            let tempHeight = cell.calculateRowHeight(viewModel)
            
            rowHeightCaches[viewModel.status.idstr ?? "-1"] = tempHeight
            
            // 3.返回行高
            return tempHeight
        }
        
        // 缓存中有就直接返回缓存中的行高
        return height
    }
}
